package com.vehiclemanagement.controller;

import com.vehiclemanagement.common.result.Result;
import com.vehiclemanagement.dto.LoginRequest;
import com.vehiclemanagement.dto.UserDTO;
import com.vehiclemanagement.entity.User;
import com.vehiclemanagement.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 处理用户登录、注册、密码重置等功能
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginRequest loginRequest) {
        log.info("用户登录请求: username={}", loginRequest.getUsername());
        
        try {
            // 进行登录验证，获取token
            String token = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
            
            // 获取用户信息
            User user = userService.getUserByUsername(loginRequest.getUsername());
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("userId", user.getId());
            result.put("username", user.getUsername());
            result.put("realName", user.getRealName());
            result.put("role", user.getRole());
            
            return Result.success("登录成功", result);
        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Boolean> register(@Valid @RequestBody UserDTO userDTO) {
        log.info("用户注册请求: username={}", userDTO.getUsername());
        
        try {
            boolean success = userService.register(userDTO);
            return success ? Result.success("注册成功", true) : Result.error("注册失败");
        } catch (Exception e) {
            log.error("注册失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestParam String username) {
        log.info("获取用户信息: username={}", username);
        
        try {
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 重置密码
     */
    @PostMapping("/resetPassword")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> resetPassword(@RequestParam Long userId, @RequestParam String newPassword) {
        log.info("重置密码: userId={}", userId);
        
        try {
            boolean success = userService.resetPassword(userId, newPassword);
            return success ? Result.success("密码重置成功", true) : Result.error("密码重置失败");
        } catch (Exception e) {
            log.error("密码重置失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
} 